
/**title:一键录屏**/ // <--- 此行必需，不得缺失
/**version:1.0.4**/ // <--- 版本号

/** tools */
var getElement = function (eleId) {
    return document.querySelector(eleId);
}
var getElementAll = function (eleId) {
    return document.querySelectorAll(eleId);
}
var displayNoneElements = function (eles) {
    if (eles && eles.length > 0) {
        eles.forEach(item => item.style.display = 'none');
    }
}

String.prototype.startWith = function (endStr) {
    var d = this.length - endStr.length;
    return (endStr.length > 0 && d >= 0 && this.indexOf(endStr) == 0)
}

String.prototype.endWith = function (endStr) {
    var d = this.length - endStr.length;
    return (d >= 0 && this.lastIndexOf(endStr) == d)
}

//[绑定监听事件]
function addMethod(node, type, method) {
    if (node.addEventListener) { // IE9以下不兼容
        node.addEventListener(type, method, false)
    } else if (node.attachEvent) { // IE独有
        node.attachEvent(`on${type}`, method)
    } else {
        node[`on${type}`] = method; // 一个元素只能绑定一个处理程序
    }
}

//[移除监听事件]
function removeMethod(node, type, method) {
    if (node.removeEventListener) { // IE9以下不兼容
        node.removeEventListener(type, method, false)
    } else if (node.detachEvent) { // IE独有
        node.detachEvent(`on${type}`, method)
    } else {
        node[`on${type}`] = method;
    }
}

function addLinkIntoHead(cssURL) {
    var head = document.getElementsByTagName('head')[0],
        linkTag = document.createElement('link');

    linkTag.id = 'dynamic-style';
    linkTag.href = cssURL;
    linkTag.setAttribute('rel', 'stylesheet');
    linkTag.setAttribute('media', 'all');
    linkTag.setAttribute('type', 'text/css');

    head.appendChild(linkTag);
}

/***********************main************************/
const SogreyRecordHtmlRootId = 'SogreyRecordHtmlRootId';
function initHtmlElements() {
    // 判断HTML element 是否已存在
    // 已存在返回
    let root = document.getElementById(SogreyRecordHtmlRootId);
    if (root) return;
    // 不存在创建

    root = document.createElement("div");
    root.id = SogreyRecordHtmlRootId;

    const style = `
  <style type="text/css">
  #${SogreyRecordHtmlRootId} {width: 4em;height: 4em;margin: 4em auto 0;font-size: 1em;line-height: 4em;color: #fff;font-weight: 700;text-transform: uppercase;top: 0;bottom: 0;right: 0em;position: fixed;align-items: center;z-index: 99999;user-select: none;cursor: pointer;  }
  #${SogreyRecordHtmlRootId} ul {list-style: none;margin: 0;padding: 0;perspective: 1000px;  }
  #${SogreyRecordHtmlRootId} ul li {display: block;background-color: #333;height: 4em;position: relative;-webkit-transition: webkit-transform 0.5s, background-color 0.5s, color 0.5s;transition: transform 0.5s, background-color 0.5s, color 0.5s;background-image: url("${base64Image}");background-size: 260px 36%;background-repeat: no-repeat; }
  #${SogreyRecordHtmlRootId} ul li:nth-child(1) {background-color: #00aced;background-position: 20px 16px;  } 
  #${SogreyRecordHtmlRootId} ul li.stop:nth-child(1) {background-position: -78px 16px;  }
  #${SogreyRecordHtmlRootId} ul li:nth-child(2) {background-color: #3b5998;transform: rotateY(-90deg);transform-origin: center right;background-position: -32px 16px;  }
  #${SogreyRecordHtmlRootId} ul li:nth-child(3) {background-color: #00a300;transform: rotateY(-90deg);transform-origin: center right;background-position: -175px 16px;  }
  #${SogreyRecordHtmlRootId} ul li:nth-child(4) {background-color: #1e7145;transform: rotateY(-90deg);transform-origin: center right;background-position: -128px 16px;  }
  #${SogreyRecordHtmlRootId} ul li:nth-child(5) {background-color: #ffc40d;transform: rotateY(-90deg);transform-origin: center right;background-position: -220px 16px;  }
  #${SogreyRecordHtmlRootId} ul li.show:nth-child(2) {transform: rotateY(0deg);  }
  #${SogreyRecordHtmlRootId} ul li.show:nth-child(3) {transform: rotateY(0deg);  }
  #${SogreyRecordHtmlRootId} ul li.show:nth-child(4) {transform: rotateY(0deg);  }
  #${SogreyRecordHtmlRootId} ul li.show:nth-child(5) {transform: rotateY(0deg);  }
  #${SogreyRecordHtmlRootId} ul li:hover {background-color: #339966;  }
  </style>
`;

    const html = `
<ul>
<li></li>
<li></li>
<li></li>
<li></li>
<li></li>
</ul>
`;

    root.innerHTML = style + html;

    document.body.appendChild(root);

    initEvent()
}

let EleRecording, ElePlay, EleSettings, EleDownload, EleGithub;

function initEvent() {
    EleRecording = document.querySelector(`#${SogreyRecordHtmlRootId} ul li:nth-child(1)`);
    ElePlay = document.querySelector(`#${SogreyRecordHtmlRootId} ul li:nth-child(2)`);
    EleSettings = document.querySelector(`#${SogreyRecordHtmlRootId} ul li:nth-child(3)`);
    EleDownload = document.querySelector(`#${SogreyRecordHtmlRootId} ul li:nth-child(4)`);
    EleGithub = document.querySelector(`#${SogreyRecordHtmlRootId} ul li:nth-child(5)`);

    addMethod(EleRecording, 'click', startRecord)
    addMethod(ElePlay, 'click', replay)
    addMethod(EleDownload, 'click', download)
    addMethod(EleSettings, 'click', function () {
        alert('敬请期待');
    })
    addMethod(EleGithub, 'click', function () {
        window.open('https://github.com/Sogrey/OneKeyJsTools', '_blank');
    })
}

let mediaRecorder;
var mediaStream //视频流
var videoBuffer = [] //保存的视频数据

// 初始化请求用户授权监控
function startRecord() {
    if (!navigator.mediaDevices || !navigator.mediaDevices.getDisplayMedia) {
        alert("当前浏览器不支持屏幕捕捉。\n\n当您看到这个提示，极大可能是由于浏览器的安全策略限制，在以下几种情况中可以正常使用：\n 1. 地址为 localhost://\n 2. 地址为 https://\n 3. 本地文件访问 file:///");
        return
    }
    reset()

    //获取视频流，这时候会弹出用户选择框，前提用户设备支持
    navigator.mediaDevices.getDisplayMedia({
        audio: false,
        video: true
        //{
        // width:750,height:450,frameRate:15,
        //}
    }).then((stream) => {
        // 对音视流进行操作
        // console.log('->', stream)
        initMediaRecorder(stream)
    });
}

// 开始录制方法
function initMediaRecorder(stream) {
    const options = {
        mimeType: "video/webm; codecs = vp8", // 媒体格式
    };
    // 创建 MediaRecorder 的实例对象，对指定的媒体流进行录制
    mediaRecorder = new MediaRecorder(stream, options);
    // 当生成媒体流数据时触发该事件，回调传参 event 指本次生成处理的媒体数据
    mediaRecorder.ondataavailable = event => {
        if (event?.data?.size > 0) {
            videoBuffer.push(event.data); // 存储媒体数据
        }
    };
    mediaRecorder.start();
    mediaStream = stream;

    EleRecording.classList.add('stop')
    ElePlay.classList.remove('show');
    EleSettings.classList.remove('show');
    EleDownload.classList.remove('show');
    EleGithub.classList.remove('show');

    removeMethod(EleRecording, 'click', startRecord)
    addMethod(EleRecording, 'click', stop)
};

function reset() {
    stopRecord()
    const video = document.querySelector(`video#${SogreyRecordHtmlRootId}_preview`);
    if (video) {
        video.parentNode.removeChild(video);
    }
    mediaRecorder = null
    mediaStream = null
    videoBuffer = []
}

/**
 * 停止录制
 */
function stopRecord() {
    if (mediaStream) {
        for (let track of mediaStream.getTracks()) {
            track.stop()
        }
    }
    mediaRecorder && mediaRecorder.state !== 'inactive' && mediaRecorder.stop()
}

function stop() {
    stopRecord()
    ElePlay.classList.add('show');
    EleSettings.classList.add('show');
    EleDownload.classList.add('show');
    EleGithub.classList.add('show');

    EleRecording.classList.remove('stop')

    addMethod(EleRecording, 'click', startRecord)
    removeMethod(EleRecording, 'click', stop)
}

// 回放录制内容
function replay() {
    const video = document.createElement("video");
    document.body.append(video)
    const blob = new Blob(videoBuffer, { type: "video/webm" });
    video.id = SogreyRecordHtmlRootId + "_preview",
    video.onerror = function() {
        alert("播放出错了，可能因为安全策略，该域名拒绝从“blob”加载媒体！可正常下载后观看！");
        if (video) {
            video.parentNode.removeChild(video);
        }
    };
    video.src = window.URL.createObjectURL(blob);
    video.srcObject = null;
    video.controls = true;
    video.style.zIndex = 999999;
    video.style.position = 'fixed';
    video.style.bottom = '10px';
    video.style.left = '10px';
    video.style.width = '500px';
    video.play();
}

function download() {
    console.log(videoBuffer)
    if (videoBuffer == null || videoBuffer.length == 0) {
        alert("没有视频数据")
        return
    }
    let blob = new Blob(videoBuffer, {
        type: "video/webm"
    });
    let url = URL.createObjectURL(blob);
    let a = document.createElement("a");
    document.body.appendChild(a);
    a.style = "display: none";
    a.href = url;
    a.download = "download.webm";
    a.click();
    window.URL.revokeObjectURL(url);
}

const base64Image = "";

if (!navigator.mediaDevices || !navigator.mediaDevices.getDisplayMedia) {
    alert("当前浏览器不支持屏幕捕捉。\n\n当您看到这个提示，极大可能是由于浏览器的安全策略限制，在以下几种情况中可以正常使用：\n 1. 地址为 localhost://\n 2. 地址为 https://\n 3. 本地文件访问 file:///");
}else{
    initHtmlElements();
}

